package com.lry.basic.netty.protocol.server;

import com.lry.basic.netty.protocol.constant.MsgType;
import com.lry.basic.netty.protocol.struct.Header;
import com.lry.basic.netty.protocol.struct.NettyMsg;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/9/12
 */
public class HeartBeatRespHandler extends ChannelInboundHandlerAdapter {
    private static final Logger logger = LoggerFactory.getLogger(HeartBeatRespHandler.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        NettyMsg nettyMsg = (NettyMsg) msg;
        if (nettyMsg.getHeader() != null && nettyMsg.getHeader().getType() == MsgType.HEARTBEAT_REQ.value()) {
            System.out.println("Receive client heart beat message : ---> {} " +nettyMsg);
            NettyMsg heartBeat = buildHeatBeat();
            System.out.println("Send heart beat response message to client : ---> {}"+ heartBeat);
            ctx.writeAndFlush(heartBeat);
        } else
            ctx.fireChannelRead(msg);
    }

    private NettyMsg buildHeatBeat() {
        NettyMsg message = new NettyMsg();
        Header header = new Header();
        header.setType(MsgType.HEARTBEAT_RESP.value());
        message.setHeader(header);
        return message;
    }
}
